<?php

namespace addons\xapply\controller;

use addons\xapply\Base;
use think\Config;
use app\common\exception\UploadException;
use app\common\library\Upload as UploadLibrary;
use app\common\model\User;

class Upload extends Base
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 头像上传
     * url: http://域名/addons/xapply/upload
     * doc: http://lutui.net/doc/app/profile-avatar.html
     */
    public function index()
    {
        Config::set('upload.cdnurl', '');
        $attachment = null;
        $file = $this->request->file('file');
        $error = '';
        try {
            $upload = new UploadLibrary($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $error = $e->getMessage();
        } catch (\Exception $e) {
            $error = $e->getMessage();
        }
        if ($error){
            return json(['error' => $error]);
        }
        $object = User::get($this->auth->id);
        $url = cdnurl($attachment->url, true);
        $object->avatar = $url;
        $object->save();
        return json(['error' => '', 'url' => $url]);
    }
}